package cn.chengpengper.rpc.enhanced.loadbalancer.hash.weight;

import cn.chengpengper.rpc.loadbalancer.base.BaseEnhancedServiceLoadBalancer;
import cn.chengpengper.rpc.protocol.meta.ServiceMeta;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class HashWeightServiceEnhancedLoadBalancer extends BaseEnhancedServiceLoadBalancer {

    @Override
    public ServiceMeta select(List<ServiceMeta> servers, int hashCode, String ip) {
        log.info("基于增强型加权Hash算法的负载均衡策略");
        servers = this.getWeightServiceMetaList(servers);
        if (servers == null || servers.isEmpty()){
            return null;
        }
        int index = Math.abs(hashCode) % servers.size();
        return servers.get(index);
    }
}

